/**
 * 路由相关工具函数
 */

import { menuList } from './menus'

/**
 * 根据菜单配置生成路由
 * @param {Array} menus 菜单配置
 * @returns {Array} 路由配置
 */
export function generateRoutes(menus = menuList) {
  const routes = []
  
  // 递归处理菜单生成路由
  const processMenus = (menuItems, parentPath = '') => {
    menuItems.forEach(menu => {
      const path = parentPath ? `${parentPath}/${menu.path}` : menu.path
      
      // 基本路由配置
      const route = {
        path,
        name: menu.name || path.replace(/\//g, '-'),
        component: menu.component,
        meta: {
          ...menu.meta,
          title: menu.meta?.title || '页面'
        }
      }
      
      // 添加到路由数组
      routes.push(route)
      
      // 递归处理子菜单
      if (menu.children && menu.children.length > 0) {
        processMenus(menu.children, path)
      }
    })
  }
  
  processMenus(menus)
  return routes
}

/**
 * 获取当前路由的面包屑
 * @param {String} path 当前路径
 * @param {Array} menus 菜单配置
 * @returns {Array} 面包屑数组
 */
export function getBreadcrumb(path, menus = menuList) {
  const breadcrumb = []
  
  // 递归查找面包屑
  const findBreadcrumb = (menuItems, currentPath, parents = []) => {
    for (const menu of menuItems) {
      const currentParents = [...parents, menu]
      
      // 找到匹配路径
      if (menu.path === currentPath) {
        breadcrumb.push(...currentParents)
        return true
      }
      
      // 检查子菜单
      if (menu.children && menu.children.length > 0) {
        const found = findBreadcrumb(menu.children, currentPath, currentParents)
        if (found) return true
      }
    }
    
    return false
  }
  
  findBreadcrumb(menus, path)
  return breadcrumb
}

/**
 * 获取路由的标题
 * @param {String} path 路由路径
 * @param {Array} menus 菜单配置
 * @returns {String} 路由标题
 */
export function getRouteTitle(path, menus = menuList) {
  let title = '页面'
  
  // 递归查找标题
  const findTitle = (menuItems, currentPath) => {
    for (const menu of menuItems) {
      if (menu.path === currentPath) {
        title = menu.meta?.title || '页面'
        return true
      }
      
      if (menu.children && menu.children.length > 0) {
        const found = findTitle(menu.children, currentPath)
        if (found) return true
      }
    }
    
    return false
  }
  
  findTitle(menus, path)
  return title
} 